from django.contrib import admin
from django import forms
from .models import ZbirdAccount, WalmartAccount, Keyword, Product, SkuKeywordsHistory, skus
import uuid
from django.utils.html import format_html
from django.utils import timezone
from django.urls import path
from django.shortcuts import render, redirect
from django.contrib import messages
import pandas as pd
from io import BytesIO

class UserAwareModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if self.user:
            self.fields['username'].initial = self.user.username

class ZbirdAccountForm(UserAwareModelForm):
    class Meta:
        model = ZbirdAccount
        fields = '__all__'

class WalmartAccountForm(UserAwareModelForm):
    class Meta:
        model = WalmartAccount
        fields = '__all__'

class KeywordForm(UserAwareModelForm):
    class Meta:
        model = Keyword
        fields = '__all__'

class ProductForm(UserAwareModelForm):
    class Meta:
        model = Product
        fields = '__all__'

class IsFollowingFilter(admin.SimpleListFilter):
    title = '是否跟卖'
    parameter_name = 'is_following' 

    def lookups(self, request, model_admin):
        return (
            (1, '是'),
            (0, '否'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            return queryset.filter(is_following=1)
        if self.value() == '0':
            return queryset.filter(is_following=0)
        return queryset

@admin.register(ZbirdAccount)
class ZbirdAccountAdmin(admin.ModelAdmin):
    form = ZbirdAccountForm
    list_display = ('tag','epname', 'loginname', 'username', 'create_date', 'update_date')
    search_fields = ('epname', 'username')
    list_filter = ('create_date', 'update_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(WalmartAccount)
class WalmartAccountAdmin(admin.ModelAdmin):
    form = WalmartAccountForm
    list_display = ('orderindex', 'username',  'tag', 'loginname', 'zbird_account', 'create_date', 'update_date')
    search_fields = ('username',)
    list_filter = ('create_date', 'update_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(Keyword)
class KeywordAdmin(admin.ModelAdmin):
    form = KeywordForm
    list_display = ('username', 'keyword', 'is_prohibited', 'create_date', 'update_date')
    search_fields = ('keyword',)
    list_filter = ('is_prohibited', 'create_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('productid','short_product_name', 'is_following', 'username',  'sku', 'upc','price', 'category', 'display_image','current_cart_seller', 'create_date', 'update_date')
    # list_editable = ('sku',)
    search_fields = ('product_name', 'sku', 'category')
    list_filter = ('category', 'is_following')
    fields = ('productid', 'product_name', 'sku', 'price', 'category', 'create_date', 'update_date')
    readonly_fields = ('create_date', 'update_date')
    actions = ['mark_as_following', 'mark_as_not_following', 'fetch_upc_action']

    def short_product_name(self, obj):
        """Display the first 25 characters of the product name followed by ellipses if needed."""
        return format_html(
            '<div style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</div>',
            obj.product_name
        )
    short_product_name.short_description = 'Product Name'

    def display_image(self, obj):
        """Display the product image in the admin list view with hover effect."""
        if obj.image:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-image" />'
                '<style>'
                '.product-image:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.image
            )
        return "No Image"
    display_image.short_description = "Image"

    def mark_as_following(self, request, queryset):
        """Mark selected products as following."""
        queryset.update(is_following=True, update_date=timezone.now())
    mark_as_following.short_description = "设为跟卖"

    def mark_as_not_following(self, request, queryset):
        """Mark selected products as not following."""
        queryset.update(is_following=False, update_date=timezone.now())
    mark_as_not_following.short_description = "设置为不跟卖"

    def fetch_upc_action(self, request, queryset):
        for product in queryset:
            product.fetch_upc()
    fetch_upc_action.short_description = "获取选中商品的UPC"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(SkuKeywordsHistory)
class SkuKeywordsHistoryAdmin(admin.ModelAdmin):
    list_display = ('sku', 'keywords', 'opdate',  'fromprice', 'toprice', 'username')
    search_fields = ('sku', 'keywords', 'username')
    list_filter = ('opdate', 'username')

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return True

class ImportForm(forms.Form):
    excel_file = forms.FileField(label='上传 SKU Excel(文件只有2列，SKU和PRICE) 文件')

@admin.register(skus)
class SkusAdmin(admin.ModelAdmin):
    list_display = ('id', 'is_following', 'sku', 'walmart_account', 'price','username', 'current_cart_seller', 'own_follow_price', 'upc', 'newprice', 'newsku', 'taxcode', 'rating', 'reviews', 'hasexcept')
    list_filter = ('walmart_account', 'username', 'current_cart_seller')
    search_fields = ('sku', 'username', 'upc')
    fields = ('sku', 'walmart_account', 'username', 'current_cart_seller', 'own_follow_price', 'upc', 'newprice', 'newsku', 'taxcode', 'rating', 'reviews', 'hasexcept')
    readonly_fields = ('id', 'username')
    actions = ['mark_as_following', 'mark_as_not_following']

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('import/', self.admin_site.admin_view(self.import_skus), name='import_skus'),
        ]
        return custom_urls + urls

    def import_skus(self, request):
        if request.method == 'POST':
            form = ImportForm(request.POST, request.FILES)
            if form.is_valid():
                excel_file = request.FILES['excel_file']
                df = pd.read_excel(BytesIO(excel_file.read()))
                walmart_account_id = request.POST.get('walmart_account')
                walmart_account = WalmartAccount.objects.get(id=walmart_account_id)
                username = request.user.username

                for sku, price in zip(df.iloc[:, 0], df.iloc[:, 1]):  # 假设 Excel 文件只有2列, SKU 和 PRICE 数据
                    skus.objects.update_or_create(
                        sku='00'+str(sku).replace('.0',''),
                        price=price,
                        walmart_account=walmart_account,
                        username=username
                    )
                messages.success(request, 'SKU,PRICE 数据导入成功！')
                return redirect('..')
        else:
            form = ImportForm()
        
        context = self.admin_site.each_context(request)
        context['opts'] = self.model._meta
        context['form'] = form
        context['walmart_accounts'] = WalmartAccount.objects.all()
        return render(request, 'admin/import_skus.html', context)

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        extra_context['import_url'] = 'import/'
        return super().changelist_view(request, extra_context=extra_context)

    def short_product_name(self, obj):
        """Display the first 25 characters of the product name followed by ellipses if needed."""
        return format_html(
            '<div style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</div>',
            obj.product_name
        )
    short_product_name.short_description = 'Product Name'

    def display_image(self, obj):
        """Display the product image in the admin list view with hover effect."""
        if obj.image:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-image" />'
                '<style>'
                '.product-image:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.image
            )
        return "No Image"
    display_image.short_description = "Image"

    def mark_as_following(self, request, queryset):
        """Mark selected products as following."""
        queryset.update(is_following=True, update_date=timezone.now())
    mark_as_following.short_description = "设为跟卖"

    def mark_as_not_following(self, request, queryset):
        """Mark selected products as not following."""
        queryset.update(is_following=False, update_date=timezone.now())
    mark_as_not_following.short_description = "设置为不跟卖"

    def save_model(self, request, obj, form, change):
        if not obj.username:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)